<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="info.name" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="info.age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="info.sex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="add">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in arr" :key="index">
          <td>{{ index + 1 }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.sex }}</td>
          <td>
            <button @click="del(index)">删除</button>
            <button @click="edital(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      arr: [
        { id: 1, name: "王金博", age: 22, sex: "男" },
        { id: 2, name: "网三", age: 27, sex: "男" },
        { id: 3, name: "妮芷", age: 22, sex: "女" },
      ],
      info: {
        name: "",
        age: "",
        sex: "",
      },
      bool: true,
    };
  },
  methods: {
    del(id) {
      this.arr = this.arr.filter((item) => item.id !== id + 1);
    },
    add() {
      if (this.bool) {
        if (this.info.name && this.info.age) {
          this.arr.push({
            id: this.arr.length ? this.arr.length + 1 : 1,
            name: this.info.name,
            age: this.info.age,
            sex: this.info.sex,
          });
          (this.info.name = ""), (this.info.age = "");
          this.info = {
            sex: "",
          };
        } else {
          alert("输入内容格式不正确");
        }
      }else{
        this.bool=true
        // console.log(this.arr[this.info.id-1]);
        this.arr[this.info.id-1].name=this.info.name
        this.arr[this.info.id-1].age=this.info.age
        this.arr[this.info.id-1].sex=this.info.sex
      }
    },
    edital(index) {
      // alert(index)
      this.bool = false;
      this.info = { ...this.arr[index] };
    },
  },
};
</script>
